package org.opsli.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class GuaGuaUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取redis缓存key
     *
     * @param pattern 缓存key
     * @return 缓存key集合
     */
    public static Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 写入redis缓存
     *
     * @param key     缓存key
     * @param value   缓存value
     * @param timeout 缓存时间
     * @param unit    缓存时间单位
     */
    public static void set(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    /**
     * 读取redis缓存
     *
     * @param key 缓存key
     * @return 缓存value
     */
    public static Object get(String key) {
        try {
            if (redisTemplate.hasKey(key)) {
                return redisTemplate.opsForValue().get(key);
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        GuaGuaUtil.redisTemplate = redisTemplate;
    }

}
